import logging
import random

from django.http import HttpResponse
from django_redis import get_redis_connection
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from celery_tasks.sms.tasks import send_sms_code
from meiduo.libs.captcha.captcha import captcha
from verifications.serializers import ImageCodeCheckSerializer
from . import constants

logger = logging.getLogger("django")


# 1.接口1--图片验证码
class ImageCodeView(APIView):
    """
    获取图片验证码
    """
    def get(self, request, image_code_id):
        """
        获取图片验证码
        :param request:
        :param image_code_id:
        :return:
        """
        # 1.获取参数--image_code_id

        # 2.校验参数--在url中通过正则校验

        # 3.生成图片验证码
        text, image = captcha.generate_captcha()

        # 4.将图片保存到redis中,并设置过期时间
        redis_conn = get_redis_connection("verify_codes")
        redis_conn.setex("image_%s" % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
        # 5.返回前端 rest_framework没有提供渲染图片的返回方法
        return HttpResponse(image, content_type="image/jpg")


# 接口2--手机验证码
# url:参数-手机号,保存在redis中的图片id, 和图片内容text
class SMSCodeView(GenericAPIView):
    """
    获取短信验证码
    """
    serializer_class = ImageCodeCheckSerializer

    def get(self, request, mobile):
        """
        :return:
        """
        # 1.接受参数

        # 2.校验参数
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        # 3.生成短信验证码
        sms_code = ("%06d") % random.randint(0, 999999)

        # 4.保存验证码 发送记录
        redis_conn = get_redis_connection("verify_codes")

        # 使用redis管道,往管道里面存数据,一次性发送到redis服务器,减少数据发生呢个次数
        # 管道只能存数据,不能取数据
        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, constants.SMG_CODE_REDIS_EXPIRES, sms_code)  # 短信验证码
        pl.setex("send_flag_%s" % mobile, constants.SMG_CODE_REDIS_EXPIRES, sms_code)  # 发送记录,发送后设为1
        # 让管道执行命令,发送数据
        pl.execute()

        # 5.发送短信
        # try:
        #     ccp = CCP()
        #     expires = constants.SMG_CODE_REDIS_EXPIRES // 60
        #     result = ccp.send_template_sms(mobile, [sms_code, expires], constants.SMS_CODE_TEMP_ID)
        # except Exception as e:
        #     logger.error("发送短信验证码[异常][ mobile: %s  message: %s  ]" %(mobile, e))
        #     return Response({"message": "failed"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        # else:
        #     if result == 0:
        #         logger.info("发送短信验证码[成功][ mobile: %s ]" % mobile)
        #     else:
        #         logger.warning("发送短信验证码[失败][ mobile:%s ]" % mobile)

        # 不再自己发短信,而是让celery的worker进行发送短信
        expires = constants.SMG_CODE_REDIS_EXPIRES // 60
        send_sms_code.delay(mobile, sms_code, expires, constants.SMS_CODE_TEMP_ID)

        # 6.返回
        return Response({"message": "OK"})
